<template>
  <div @back="() => $router.go(-1)">
    <div class="permissionContent">
      <a-tabs v-model="currentTab" @change="tabsChange">
        <a-tab-pane key="1" tab="权限模版">
          <a-row :gutter="48">
            <a-col :md="12" :sm="24">
              <a-form-model-item ref="ptsVisible" prop="ptsVisible">
                <a-radio-group v-model="systemId" @change="gettempPermissionListTemp">
                  <a-radio :value="1"> PC权限 </a-radio>
                  <a-radio :value="4"> 小程序权限 </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <div class="but-node">
                <a-button type="primary" @click="nodeSet(1)">添加根节点</a-button>
                <a-button type="primary" :disabled="!currentAlone.id || currentAlone.module == 2" @click="nodeSet(2)">
                  添加子节点
                </a-button>
                <a-button type="primary" :disabled="!currentAlone.id" @click="nodeSet(3)">修改该节点</a-button>
                <a-button type="primary" :disabled="!currentAlone.id">
                  <a-popconfirm title="是否确认删除？" @confirm="handleDelete">
                    <a>删除该节点</a>
                  </a-popconfirm>
                </a-button>
              </div>
            </a-col>
          </a-row>
          <PermissionTable ref="temTable" :is-edit="true" :code="formData.code" :permission="permission"
                           @check="checkAlone" :isAlone="true"
          />
        </a-tab-pane>

        <a-tab-pane key="2" tab="权限同步">
          <a-row :gutter="12">
            <a-col :md="12" :sm="24">
              <a-form-model-item ref="ptsVisible" prop="ptsVisible">
                <a-radio-group v-model="systemId1" @change="gettempPermissionListAllTemp">
                  <a-radio :value="1"> PC权限 </a-radio>
                  <a-radio :value="4"> 小程序权限 </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <div class="but-node">
                <a-button type="primary" :disabled="!currentMore.length">
                  <a-popconfirm title="是否确认同步权限至项目？" @confirm="syncPermiss">
                    <a>同步权限至项目</a>
                  </a-popconfirm>
                </a-button>
                <a-button type="primary" :disabled="!currentMore.length" @click="roleSet(1)">赋予权限至角色</a-button>
                <a-button type="primary" :disabled="!currentMore.length" @click="roleSet(2)">剔除角色权限</a-button>
                <a-button type="primary" @click="getStatus">获取同步状态</a-button>
              </div>
            </a-col>
          </a-row>
          <PermissionTable ref="syncTable" :is-edit="true" :permission="permission1" @check="checkMore"
                           :isMore="true"
          />
        </a-tab-pane>
      </a-tabs>
    </div>

    <a-modal
      :visible="modalVisible"
      :title="modalTitle"
      :width="600"
      :footer="null"
      @cancel="cancel"
    >
      <a-form-model
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="formData.name" :maxLength="30" placeholder="请输入名称" />
        </a-form-model-item>
        <a-form-model-item label="权限code" prop="code">
          <a-input v-model="formData.code" placeholder="请输入权限code" />
        </a-form-model-item>
        <a-form-model-item v-if="modalTitle == '添加子节点'" label="模块类型" prop="module">
          <a-radio-group v-model="formData.module">
            <a-radio :value="1">菜单资源</a-radio>
            <a-radio :disabled="currentAlone.module == 0" :value="2">按钮</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="页面路由" prop="url">
          <a-input v-model="formData.url" placeholder="请输入页面路由" />
        </a-form-model-item>
        <a-form-model-item label="是否公用权限" prop="isPublic">
          <a-radio-group v-model="formData.isPublic">
            <a-radio value="1">是</a-radio>
            <a-radio value="-1">否</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="置灰角色" prop="greyRoles">
          <a-select v-model="formData.greyRoles" mode="multiple" placeholder="请选择置灰角色">
            <a-select-option v-for="item in roleList" :key="item" :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选中角色" prop="selectedRoles">
          <a-select v-model="formData.selectedRoles" mode="multiple" placeholder="请选择选中角色">
            <a-select-option v-for="item in roleList" :key="item" :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-row :gutter="48">
          <a-col :md="24" :sm="24">
            <a-button
              type="primary"
              :loading="btnLoading"
              @click="onSubmit"
              style="float: right"
            >
              确 认
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

    <a-modal
      :visible="modalVisible1"
      :title="modalTitle1"
      :width="600"
      :footer="null"
      @cancel="cancel1"
    >
      <a-form-model
        ref="formRef1"
        :model="formData1"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="角色权限" prop="roleCodes">
          <a-select v-model="formData1.roleCodes" mode="multiple" placeholder="请选择角色权限">
            <a-select-option v-for="item in roleList" :key="item" :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item v-if="formData1.systemId == 2" label="是否为ipad" prop="isPad">
          <a-radio-group v-model="formData1.isPad">
            <a-radio value="1">是</a-radio>
            <a-radio value="0">否</a-radio>
          </a-radio-group>
        </a-form-model-item> -->
        <a-row :gutter="48">
          <a-col :md="24" :sm="24">
            <a-button
              type="primary"
              :loading="btnLoading"
              @click="onSubmit1"
              style="float: right"
            >
              确 认
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { tempPermissionListTemp, tempPermissionListRole, tempPermissionListAllTemp, tempPermissionInsert, tempPermissionUpdate, tempPermissionDelete, tempPermissionSyncForPro, tempPermissionSyncForRoleAdd, tempPermissionSyncForRoleDel, tempPermissionGetStatus } from '@/api/system/permissions.js'
import PermissionTable from './components/components/permissionTable.vue'
export default {
  components: {
    PermissionTable
  },
  data () {
    return {
      currentAlone: {},
      currentMore: [],
      currentTab: '1',
      btnLoading: false,
      systemId: 1,
      systemId1: 1,
      permission: [],
      permission1: [],
      modalVisible: false,
      modalVisible1: false,
      modalTitle: '添加根节点',
      modalTitle1: '赋予权限至角色',
      roleList: [],
      formData: {
        id: '',
        pid: 0,
        systemId: '',
        name: '',
        code: '',
        module: '',
        url: '',
        isPublic: '',
        greyRoles: [],
        selectedRoles: []
      },
      formData1: {
        list: [],
        systemId: '',
        // isPad: 0,
        roleCodes: []
      },
      rules: {
        name: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        // code: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        module: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        url: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        // isPublic: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        greyRoles: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        selectedRoles: [{ required: true, message: '此项为必填项', trigger: 'change' }],
        roleCodes: [{ required: true, message: '此项为必填项', trigger: 'change' }]
        // isPad: [{ required: true, message: '此项为必填项', trigger: 'change' }]
      },
      labelCol: {
        span: 5
      },
      wrapperCol: {
        span: 18
      }
    }
  },
  mounted () {
    this.gettempPermissionListTemp()
    this.gettempPermissionListAllTemp()
    this.gettempPermissionListRole()
  },
  methods: {
    // 递归 全清空
    recursiveProcess (data) {
      if (!data || data.length === 0) return
      data.forEach(v => {
        this.$set(v, 'checked', false)
        if (v.child && v.child.length > 0) {
          v.child.forEach((cv) => {
            this.$set(cv, 'checked', false)
          })
        }
        if (v.children && v.children.length > 0) {
          this.recursiveProcess(v.children)
        }
      })
    },
    gettempPermissionListTemp () {
      tempPermissionListTemp({ systemId: this.systemId }).then(res => {
        this.permission = res
        this.$store.commit('SET_CHECK_ALONE', {})
        this.currentAlone = {}
        this.formData = {
          id: '',
          pid: 0,
          systemId: '',
          name: '',
          code: '',
          module: '',
          url: '',
          isPublic: '',
          greyRoles: [],
          selectedRoles: []
        }
      })
    },
    gettempPermissionListAllTemp () {
      tempPermissionListAllTemp({ systemId: this.systemId1 }).then(res => {
        this.permission1 = res
        this.$store.commit('SET_CHECK_MORE', [])
        this.currentMore = {}
        this.formData1 = {
          list: [],
          systemId: '',
          // isPad: '',
          roleCodes: []
        }
      })
    },
    gettempPermissionListRole () {
      tempPermissionListRole().then(res => {
        this.roleList = res
      })
    },
    tabsChange(e) {
      if (e === '1') {
        this.systemId = 1
        this.gettempPermissionListTemp()
      } else {
        this.systemId1 = 1
        this.gettempPermissionListAllTemp()
      }
    },
    checkAlone (val) {
      this.currentAlone = JSON.parse(JSON.stringify(val))
      this.currentAlone.greyRoles = this.currentAlone.greyRoles.split(',')
      this.currentAlone.selectedRoles = this.currentAlone.selectedRoles.split(',')
    },
    cancel () {
      this.modalVisible = false
    },
    nodeSet (type) {
      this.modalVisible = true
      switch (type) {
        case 1:
          this.modalTitle = '添加根节点'
          this.formData = {
            pid: 0,
            systemId: this.systemId,
            module: 0,
            name: '',
            code: '',
            url: '',
            isPublic: '',
            greyRoles: [],
            selectedRoles: []
          }
          break
        case 2:
          this.modalTitle = '添加子节点'
          this.formData = {
            pid: this.currentAlone.id,
            systemId: this.systemId,
            module: 1,
            name: '',
            code: '',
            url: '',
            isPublic: '',
            greyRoles: [],
            selectedRoles: []
          }
          break
        case 3:
          this.modalTitle = '修改该节点'
          this.formData = JSON.parse(JSON.stringify(this.currentAlone))
          break
      }
    },
    onSubmit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.btnLoading = true
          let data = JSON.parse(JSON.stringify(this.formData))
          data.greyRoles = data.greyRoles.join(',')
          data.selectedRoles = data.selectedRoles.join(',')
          if (data.id) {
            tempPermissionUpdate({ ...data }).then(res => {
              this.btnLoading = false
              this.modalVisible = false
              this.gettempPermissionListTemp()
              this.$message.success('修改成功')
            }).catch(() => {
              this.btnLoading = false
            })
          } else {
            tempPermissionInsert({ ...data }).then(res => {
              this.btnLoading = false
              this.modalVisible = false
              this.gettempPermissionListTemp()
              this.$message.success('添加成功')
            }).catch(() => {
              this.btnLoading = false
            })
          }
        }
      })
    },
    handleDelete () {
      tempPermissionDelete({
        id: this.currentAlone.id
      }).then(res => {
        this.$message.success('删除成功！')
        this.gettempPermissionListTemp()
      }).catch(_ => {

      })
    },
    cancel1 () {
      this.modalVisible1 = false
    },
    checkMore (val) {
      this.currentMore = val
      this.formData1.list = JSON.parse(JSON.stringify(val))
      this.formData1.systemId = this.systemId1
      // this.formData1.isPad = 0
    },
    roleSet (type) {
      this.modalVisible1 = true
      this.modalTitle1 = type === 1 ? '赋予权限至角色' : '剔除角色权限'
      this.formData1.roleCodes = []
      // this.formData1.isPad = ''
    },
    syncPermiss () {
      this.$message.success('已点击，请等待结果！')
      this.currentMore = []
      this.recursiveProcess(this.permission1)
      this.$store.commit('SET_CHECK_MORE', [])
      tempPermissionSyncForPro(JSON.stringify({
        list: this.formData1.list,
        systemId: this.formData1.systemId
      })).then(res => {
        this.$message.success('操作成功！')
        this.gettempPermissionListAllTemp()
      }).catch(_ => {

      })
    },
    onSubmit1 () {
      this.$refs.formRef1.validate(valid => {
        if (valid) {
          this.btnLoading = true
          this.$message.success('已点击，请等待结果！')
          this.btnLoading = false
          this.modalVisible1 = false
          this.currentMore = []
          this.recursiveProcess(this.permission1)
          this.$store.commit('SET_CHECK_MORE', [])
          if (this.modalTitle === '赋予权限至角色') {
            tempPermissionSyncForRoleAdd(JSON.stringify({
              list: this.formData1.list,
              roleCodes: this.formData1.roleCodes.join(','),
              systemId: this.formData1.systemId
              // isPad: this.formData1.isPad
            })).then(res => {
              this.btnLoading = false
              this.modalVisible1 = false
              this.gettempPermissionListAllTemp()
              this.$message.success('赋予成功')
            }).catch(() => {
              this.btnLoading = false
            })
          } else {
            tempPermissionSyncForRoleDel(JSON.stringify({
              list: this.formData1.list,
              roleCodes: this.formData1.roleCodes.join(','),
              systemId: this.formData1.systemId
              // isPad: this.formData1.isPad
            })).then(res => {
              this.btnLoading = false
              this.modalVisible1 = false
              this.gettempPermissionListAllTemp()
              this.$message.success('剔除成功')
            }).catch(() => {
              this.btnLoading = false
            })
          }
        }
      })
    },
    getStatus() {
    tempPermissionGetStatus().then(res => {
      this.$message.success(res)
    }).catch(_ => {

    })
  }
  }
}
</script>
<style lang="less" scoped>
.permissionContent {
  background: white;
  margin: 0 auto;
  padding: 20px;

  .but-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>